def solve(lst1,lst2):
    st=[]
    i,j=0,0
    n=len(lst1)
    while j<n:
        if lst2[j] in st:
            if lst2[j]!=st[-1]: 
                print('***',i,j,st)
                return False 
            else:
                print('pop',i,j,st)
                st.pop()
                j+=1
        else:
            while i<n and lst1[i]!=lst2[j]:
                print('add',i,j,st)
                st.append(lst1[i])
                i+=1
            if i==n: return False 
            i+=1
            j+=1
    return True

print(solve([1,2,3,4,5],[4,5,3,2,1]))
print(solve([1,2,3,4,5],[4,3,5,1,2]))
